<?php
/**
 * Form Plugin (mail component): sends a mail with form contents
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Esther Brunner <wikidesign@gmail.com>  
 */
 
if (!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../../../').'/');
if (!defined('DOKU_LF')) define('DOKU_LF', "\n");

require_once(DOKU_INC.'inc/init.php');
require_once(DOKU_INC.'inc/common.php');
require_once(DOKU_INC.'inc/pageutils.php');
require_once(DOKU_INC.'inc/auth.php');
require_once(DOKU_INC.'inc/io.php');

global $conf, $INFO;

$ns    = cleanID($_POST['ns']);
$title = stripctl($_POST['title']);
$id    = ($ns ? $ns.':' : '').cleanID($title);
$file  = wikiFN($id);
$auth  = auth_quickaclcheck($ns.':*');

// check permission first
if ($auth < AUTH_CREATE){
  msg('no permission to create file', -1);
  die();
}

// some default stuff

$replace = array(
  '@ID@'    => $id,
  '@NS@'    => $ns,
  '@PAGE@'  => $title,
  '@DATE@'  => date($conf['dformat']),
);
// handle uploaded files
$uploads = form_uploads($ns, $auth);
$replace['@FILES@'] = implode("\n  * ", $uploads);
$replace = array_merge($uploads, $replace);

$tpl = io_readFile(dirname($file).'/_template.txt');
if (!$tpl) $tpl = io_readFile(DOKU_PLUGIN.'form/_template.txt');

// do some additional replacements with $_POSTs
foreach ($_POST as $key => $data){
  // ignore DokuWiki internal stuff
  if ((substr($key, 0, 2) === 'DW')
    || (substr($key, 0, 5) === 'DOKU_')
    || (substr($key, 0, 8) === 'DokuWiki'))
    continue;
    
  // ignore some stuff that is handled by default
  if (in_array(strtolower($key), array('id', 'ns', 'page'))) continue;
  
  $search = '@'.strtoupper($key).'@';
  $replace[$search] = $data;
}
// fill user dependent stuff if it has not been filled otherwise
if (!isset($replace['@USER@'])) $replace['@USER@'] = $_SERVER['REMOTE_USER'];
if (!isset($replace['@NAME@'])) $replace['@NAME@'] = $INFO['userinfo']['name'];
if (!isset($replace['@MAIL@'])) $replace['@MAIL@'] = $INFO['userinfo']['mail'];

$tpl = str_replace(array_keys($replace), array_values($replace), $tpl);

io_writeWikiPage($file, $tpl, $id);

// restore some DokuWiki parameters and go to a thanks page
$_REQUEST['id'] = $id;
header('Location: '.wl($id));

/*---------- Functions ----------*/

/**
 * Handles media file uploads
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author Esther Brunner <wikidesign@gmail.com>
 *
 * @return array replace patterns for each successful upload
 */
function form_uploads($ns, $auth){
  if (empty($_FILES)) return '';
  if ($auth < AUTH_UPLOAD) return '';
  
  require_once (DOKU_INC.'inc/confutils.php');
  require_once (DOKU_INC.'inc/media.php');
  global $lang;
  global $conf;
  
  $uploads = array();

  foreach ($_FILES as $key => $file){
    // get file and id
    $id = $file['name'];

    // check extension
    list($ext, $mime) = mimetype($id);

    // get filename
    $id   = cleanID($ns.':'.$id);
    $fn   = mediaFN($id);

    // get filetype regexp
    $types = array_keys(getMimeTypes());
    $types = array_map(create_function('$q', 'return preg_quote($q,"/");'), $types);
    $regex = join('|', $types);

    // because a temp file was created already
    if (preg_match('/\.('.$regex.')$/i', $fn)){
      //check for overwrite
      if (@file_exists($fn)) msg($lang['uploadexist'], 0);

      // check for valid content
      $ok = media_contentcheck($file['tmp_name'], $mime);
      if ($ok == -1) msg(sprintf($lang['uploadbadcontent'],".$ext"), -1);
      elseif ($ok == -2) msg($lang['uploadspam'], -1);
      elseif ($ok == -3) msg($lang['uploadxss'], -1);

      // prepare directory
      io_createNamespace($id, 'media');
      if (move_uploaded_file($file['tmp_name'], $fn)) {
        // Set the correct permission here.
        // Always chmod media because they may be saved with different permissions than expected from the php umask.
        // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.)
        chmod($fn, $conf['fmode']);
        msg($lang['uploadsucc'], 1);
        media_notify($id, $fn, $mime);
        $key = '@'.strtoupper($key).'@';
        $uploads[$key] = '{{'.$id.'|'.$file['name'].'}}';
      }else{
        msg($lang['uploadfail'], -1);
      }
    }else{
      msg($lang['uploadwrong'], -1);
    }
  }
  
  // return replace patterns for successful uploads
  return $uploads;
}
 
//Setup VIM: ex: et ts=4 enc=utf-8 :
